package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.validation.ObjectError;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author:篍
 * @Date: 2025/08/20 10:21
 * @Description:
 */
@Service
public class WechatServiceImpl implements WechatService {

    //登录code
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    @Override
    public String getOpenid(String code) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("appid", appid);
            params.put("secret", secret);
            params.put("js_code", code);
            String result = HttpUtil.get(REQUEST_URL, params);
            JSONObject jsonObject = JSONUtil.parseObj(result);
            if (Objects.nonNull(jsonObject.getInt("errcode"))) {
                throw new BaseException("获取微信OpenId失败",jsonObject.getStr("errmsg"));
            }

            return jsonObject.getStr("openid");
        } catch (BaseException e) {
            throw new BaseException("网络繁忙",e.getMessage());
        }
    }

    @Override
    public String getToken() {
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        String result = HttpUtil.get(TOKEN_URL, params);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (Objects.nonNull(jsonObject.getInt("errcode"))) {
            throw new BaseException("获取access_token失败",jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");
    }

    @Override
    public String getPhone(String detailCode) {
        String token = getToken();
        Map<String, Object> params = new HashMap<>();
        params.put("code", detailCode);
        String result = HttpUtil.post(PHONE_REQUEST_URL + token, JSONUtil.toJsonStr(params));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (!jsonObject.getInt("errcode").equals(0)){
            throw new BaseException("获取手机号失败",jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }
}
